package reflection;

import java.lang.reflect.Field;

/**
 * @author DCSGO
 * @version 1.0
 * 反射设置对象属性
 */
public class ReflectionSetField {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> cls = Class.forName("reflection.Dog");
        Object dog = cls.newInstance();
        //1.设置 public 属性
        Field name = cls.getField("name");
        name.set(dog, "旺财");
        System.out.println(dog);
        //Dog{name='旺财', weight=0.0, cnt=0}

        //2.设置非 public 属性
        Field weight = cls.getDeclaredField("weight");
        weight.setAccessible(true);//非 public 属性也需要爆破
        weight.set(dog, 3.1415);
        System.out.println(dog);
        //Dog{name='旺财', weight=3.1415, cnt=0}

        //3.设置 static 属性
        Field cnt = cls.getDeclaredField("cnt");
        //非 public 的成员都要用 Declared 相关方法 并爆破
        cnt.setAccessible(true);
        cnt.set(dog, 1);
        System.out.println(dog);
        //Dog{name='旺财', weight=3.1415, cnt=1}
        //也可以将 set(Object obj, Object value) 中的 obj 设置为 null 仅适用于静态成员
        cnt.set(null, 2);
        System.out.println(dog);
        //Dog{name='旺财', weight=3.1415, cnt=2}
    }
}

class Dog {
    private static int cnt;
    public String name;
    private double weight;

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", weight=" + weight +
                ", cnt=" + Dog.cnt +
                '}';
    }
}